const NODE_ENV = process.env.NODE_ENV || 'development';
const utils = require('./utils');
const config = require('./config');
const webpack = require('webpack');
const WebpackAssets = require('assets-webpack-plugin');
const createLintingRule = () => ({
  test: /\.(js)$/,
  loader: 'eslint-loader',
  enforce: 'pre',
  include: [utils.resolve('src'), utils.resolve('test')],
  options: {
    formatter: require('eslint-friendly-formatter'),
    emitWarning: !config.dev.showEslintErrorsInOverlay
  }
});
const entry = utils.getEntry();

const SVGFont = require('./plugins/svgfont');
const sprite = require('./plugins/sprite');
// 导出配置
module.exports = {
  entry, // 获得入口文件
  context: utils.resolve(), // 上下文一定是跟目录
  output: {
    path: config.dev.assetsRoot, // 文件输出到的地方必须是一个绝对路径
    publicPath: config.dev.assetsPublicPath, // 前缀
    filename: '[name].js',
    chunkFilename: 'js/chunk/[name].js',
  },
  resolve: {
    extensions: ['.js', '.json', '.scss'],
    modules: ['node_modules'],
    alias: {
      '~': utils.resolve(), // 定义别名
      '@': utils.resolve('src/static'), // 定义别名
    }
  },
  module: {
    // 解析规则
    rules: [
      ...(config.dev.useEslint ? [createLintingRule()] : []),
      {
        test: /\.js$/,
        include: [
          utils.resolve('src'),
          utils.resolve('node_modules/@acgn'),
          utils.resolve('node_modules/@colpu')
        ],
        loader: 'babel-loader', // 对所有js进行babel-loader转换
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'file-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('images/[name].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'file-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath(`fonts/[name].[${config.build.chunkhash}].[ext]`)
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        type: 'asset/resource',
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath(`media/[name].[${config.build.chunkhash}].[ext]`)
        }
      },

      {
        // 将jquery暴露到windows全局变量
        test: require.resolve('jquery'),
        loader: 'expose-loader',
        options: {
          exposes: ['$', 'jQuery'],
        },
      },
    ]
  },

  plugins: [

    // 定义全局变量插件
    new webpack.DefinePlugin({
      'process.env': require(`./config/${NODE_ENV}.env`)
    }),

    // 全局挂载插件在写模块时不在引入jquery
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery',
      'window.$': 'jquery'
    }),

    // asset资源输出目录
    new WebpackAssets({
      includeAllFileTypes: false,
      fileTypes: ['js', 'css'],
      path: utils.resolve(),
      filename: `asset.${NODE_ENV}.json`
    }),

    new SVGFont(),
    ...sprite
  ]
};
